from selenium import webdriver
from concurrent.futures import ThreadPoolExecutor, as_completed
import time

# ChromeDriver 配置
chrome_options = webdriver.ChromeOptions()
# chrome_options.add_argument("--headless")  # 无头模式，避免弹出浏览器窗口
# chrome_options.add_argument("--no-sandbox")
# chrome_options.add_argument("--disable-dev-shm-usage")


# 任务函数：每个线程执行的任务
def run_chrome_instance(username):
    print(f"启动 ChromeDriver 处理用户: {username}")
    driver = webdriver.Chrome(options=chrome_options)

    try:
        # 打开网页并执行与该用户相关的操作
        driver.get("https://www.google.com")
        print(f"用户 {username} 页面标题: {driver.title}")
        # 模拟与页面的交互
        time.sleep(2)  # 模拟一些操作耗时
    finally:
        # 确保每次都关闭 ChromeDriver
        driver.quit()
        print(f"已释放 ChromeDriver 资源，处理完用户: {username}")


# 模拟 100 个用户名任务
usernames = [f"user_{i}" for i in range(1, 101)]

# 使用线程池来管理 5 个 ChromeDriver 线程的并发执行
with ThreadPoolExecutor(max_workers=5) as executor:
    # 提交 100 个任务，但最多 5 个 ChromeDriver 并发执行
    future_to_username = {executor.submit(run_chrome_instance, username): username for username in usernames}

    # 逐一完成任务并处理结果
    for future in as_completed(future_to_username):
        username = future_to_username[future]
        try:
            future.result()  # 获取任务的结果，捕获并处理潜在异常
        except Exception as e:
            print(f"用户 {username} 的任务出现异常: {e}")

print("所有任务已完成。")
